from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
from django.db.models import Q
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import viewsets, authentication
from rest_framework.pagination import PageNumberPagination
from rest_framework.permissions import IsAuthenticated
from rest_framework import filters
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
# from user.filters import UserFilter
from user.serializers import UserJWTSerializer, UserCreateSerializer, UserListSerializer

# Create your views here.

User = get_user_model()

class CustomBackend(ModelBackend):
    """
    自定义用户验证
    """
    def authenticate(self, request, username=None, password=None, **kwargs):
        try:
            user = User.objects.get(Q(username=username) | Q(mobile=username))
            if user.check_password(password):
                return user
        except Exception as e:
            return None

def jwt_response_payload_handler(token, user=None, request=None):
    return {
        'token': token,
        'user': UserJWTSerializer(user, context={'request': request}).data
    }




class UsersPagination(PageNumberPagination):
    page_size = 10
    page_size_query_param = 'page_size'
    page_query_param = "page"
    max_page_size = 20


class  UserViewSet(viewsets.ModelViewSet):
    """
        用户信息
        list:
           获取用户信息
        create:
           添加用户信息
        retrieve:
            获取单独用户的信息
        update:
           全部更新用户信息
        partial_update:
            部分
            更新用户信息
        delete:
           删除用户信息
    """
    authentication_classes = (JSONWebTokenAuthentication, authentication.SessionAuthentication)  # jwt和session认证
    pagination_class = UsersPagination  # 分页
    filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)  # 过滤，一般为choice和外键
    # filter_class = UserFilter
    search_fields = ('username', 'mobile',)  # 搜索，文字字段，
    ordering_fields = ('gender',)  # 排序

    def get_serializer_class(self):
        #  详情
        if self.action in ["create", "partial_update"]:
            return  UserCreateSerializer
        return UserListSerializer

    def get_permissions(self):  # 动态获取权限
        if self.action in ["list", "create"]:  # 用户注册和查看时，不需要权限认证
            return []
        return [IsAuthenticated()]


    def get_queryset(self):
        if self.request.user.is_superuser:
            queryset = User.objects.filter(is_active=1)
        else:
            queryset =  User.objects.filter(is_superuser=0,is_active=1,school__area=self.request.user.school.area)
        return queryset